import 'package:eh_mobile/common/routers/index.dart';
import 'package:eh_mobile/pages/main/homepage/index.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import '../../../../common/apis/homepage.dart';
import '../../../../common/store/user_store.dart';
import '../../../../common/utils/toast/bnw_toast.dart';

class BindDeviceLoginController extends GetxController {
  String circleProgressViewId = "circleProgressViewId";
  String richTextViewId = "richTextViewId";
  String cancelBtnId = "cancelBtnId";
  String bindBtnId = "bindBtnId";
  bool isConnectSuccess = true;
  double progress = 0;
  late Function refreshBlock;

  // 根据扫描的二维码数据获取mobile_token
  void mobileBindUrl(String codeStr) async {
    HomepageAPI.getActivePairCode(codeStr).then((value) {
      if (value.keys.contains('statusCode') && value['statusCode'] != 200) {
        String msg = value['message'];
        if (msg.contains('exist')) {
          BnwToast.showView(Get.context!, infoStr: '该设备已绑定过，无需绑定');
          UserStore().saveBindPhone(true);
          Get.offAll(const HomepagePage());
        } else {
          BnwToast.showView(Get.context!, infoStr: '绑定失败,请重试');
          update([richTextViewId, cancelBtnId, bindBtnId]);
          getBackToFront();
        }
      } else {
        UserStore().saveBindPhone(true);
        progress = 1;
        update([circleProgressViewId]);
        Future.delayed(const Duration(seconds: 2)).then((value) {
          Get.to(const HomepagePage());
        });
      }
    });
  }

  //返回到前一页的逻辑
  void getBackToFront() {
    Future.delayed(const Duration(seconds: 2)).then((value) {
      try {
        Navigator.popUntil(Get.context!, ModalRoute.withName(RouteNames.LOGIN));
      } catch (e) {
        Get.toNamed(RouteNames.LOGIN);
      }
    });
  }
}
